/*
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 * 
 */
package authentication;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.activation.MimetypesFileTypeMap;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        HttpEntity entity;
        List<Cookie> cookies;
        try {
            /*
             * use username and password to sign in CQ
             */
            HttpPost httpost = new HttpPost("http://localhost:4502/libs/cq/core/content/login.html/j_security_check");
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("j_username", "admin"));
            nvps.add(new BasicNameValuePair("j_password", "admin"));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

            response = httpclient.execute(httpost);
            entity = response.getEntity();

            System.out.println("Login form get: " + response.getStatusLine());
            System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }

            /*
             * send a request post in order to upload a file
             */
            final String actionUrl = "http://localhost:4502/apps/fsnext/services.rosterPhoto.html/226893/290836";
            final String imageAbsolutePath = "D:/10293/290831/images3.jpg";
            final String imageFieldName = "image";
            final String isProfileFieldName = "isProfile";

            HttpPost httppost = new HttpPost(actionUrl);
            File imageFile = new File(imageAbsolutePath);
            MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            ContentBody bin = new FileBody(imageFile, mimeTypesMap.getContentType(imageFile));
            /**
             * set this field as on/off/null
             */
            StringBody isProfile = new StringBody("off");

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart(imageFieldName, bin);
            reqEntity.addPart(isProfileFieldName, isProfile);

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }
        }
    }
}
